package chat

import (
	"counter-help/admin/server/model/chat"
	chatReq "counter-help/admin/server/model/chat/request"
	"counter-help/admin/server/model/common/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

type SystemMessageApi struct{}

// CreateSystemMessage 发布系统消息
func (s *SystemMessageApi) CreateSystemMessage(c *gin.Context) {
	var message chatReq.CreateSystemMessage
	if err := c.ShouldBindJSON(&message); err != nil {
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}
	newMessage := chat.SystemMessage{
		Title:   message.Title,
		Content: message.Content,
	}
	if err := systemMessageService.CreateSystemMessage(&newMessage); err != nil {
		response.FailWithMessage("发布系统消息失败: "+err.Error(), c)
		return
	}
	response.OkWithMessage("发布成功", c)
}

// 更新系统消息
func (s *SystemMessageApi) UpdateSystemMessage(c *gin.Context) {
	var updateMessage chatReq.UpdateSystemMessage
	if err := c.ShouldBindJSON(&updateMessage); err != nil {
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	if updateMessage.ID == 0 {
		response.FailWithMessage("ID 不能为空", c)
		return
	}

	// 创建需要更新的消息数据
	newMessage := chat.SystemMessage{
		Title:   updateMessage.Title,
		Content: updateMessage.Content,
	}

	// 调用服务方法更新消息
	if err := systemMessageService.UpdateSystemMessage(uint(updateMessage.ID), &newMessage); err != nil {
		response.FailWithMessage("更新失败: "+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// 删除系统消息
func (s *SystemMessageApi) DeleteSystemMessage(c *gin.Context) {
	idStr := c.Query("ID")
	fmt.Println("删除系统消息", idStr)
	id, err := strconv.Atoi(idStr)
	if err != nil {
		response.FailWithMessage("ID 无效", c)
		return
	}

	if err := systemMessageService.DeleteSystemMessage(uint(id)); err != nil {
		response.FailWithMessage("删除失败: "+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// 获取所有系统消息
func (s *SystemMessageApi) GetSystemMessages(c *gin.Context) {
	messages, err := systemMessageService.GetSystemMessages()
	if err != nil {
		response.FailWithMessage("获取系统消息失败: "+err.Error(), c)
		return
	}
	response.OkWithDetailed(messages, "获取成功", c)
}
